package com.ajaxlord.confluence.nest;

import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.pages.Page;
import com.atlassian.confluence.pages.PageManager;
import com.atlassian.confluence.renderer.PageContext;
import com.atlassian.confluence.util.GeneralUtil;
import com.atlassian.renderer.RenderContext;
import com.atlassian.renderer.v2.macro.MacroException;
import com.atlassian.renderer.v2.macro.basic.PanelMacro;
import com.atlassian.renderer.v2.RenderMode;
import com.opensymphony.util.TextUtils;

import java.util.Map;

public class NestMacro extends PanelMacro {
    private PageManager pageManager;
    private ContentPropertyManager contentPropertyManager;

    public void setPageManager(PageManager pageManager) {
        this.pageManager = pageManager;
    }

    public void setContentPropertyManager(ContentPropertyManager contentPropertyManager) {
        this.contentPropertyManager = contentPropertyManager;
    }

    public boolean isInline() {
        return true;
    }

    public boolean hasBody() {
        return true;
    }

    public RenderMode getBodyRenderMode() {
        return RenderMode.ALL;
    }

    public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException {
        if ("true".equals(parameters.get("nopanel"))) {
            return getBodyContent(parameters, "", renderContext);
        } else {
            return super.execute(parameters, body, renderContext);
        }
    }

    public boolean suppressMacroRenderingDuringWysiwyg() {
        return true;
    }

    protected String getTitle(Map parameters, String body, RenderContext renderContext) {
        return GeneralUtil.unescapeEntities(getPageTitle(parameters));
    }

    protected String getBodyContent(Map parameters, String body, RenderContext renderContext) throws MacroException {
        PageContext context = (PageContext) renderContext;
        String pageTitle = getPageTitle(parameters);
        Page page = pageManager.getPage(context.getSpaceKey(), pageTitle);

        if (page == null) {
            return "The page " + pageTitle + " does not exist.";
        }

        String nestKeyName = (String) parameters.get(NestExportMacro.NEST_KEY_NAME);
        if (nestKeyName == null)
            nestKeyName = "";
        else
            nestKeyName = "." + nestKeyName;
        return TextUtils.noNull(contentPropertyManager.getTextProperty(page, NestExportMacro.NEST_KEY + nestKeyName));
    }

    private String getPageTitle(Map parameters) {
        String pageTitle = TextUtils.noNull((String) parameters.get("pageTitle")).trim();
        if (pageTitle.length() == 0) {
            pageTitle = TextUtils.noNull((String) parameters.get("0")).trim();
        }
        return pageTitle;
    }
}
